// pages/classify/classify.js
var http = require("../../utils/http.js");

Page({
  switchSearch(e) {
    wx.navigateTo({
      url: '/pages/search/search',
      success: function(res) {},
      fail: function() {},
      complete: function() {}
    });
  },
  /**
   * 页面的初始数据
   */
  data: {
    activeClassify: 0,
    classifys: [],
    products: []
  },
  getDetail(e) {
    let id = e.currentTarget.dataset.id;

    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id,
    })
  },
  addCart(e) {
    let index = Number.parseInt(e.currentTarget.dataset.index);
    let product_id = this.data.products[index].id;
    let price = Number.parseFloat(this.data.products[index].sale_price);

    let params = {
      user_id: wx.getStorageSync('is_login'),
      product_id: product_id,
      quantity: 1,
      price: price,
      account: price,
      checked: true
    }
    http.request('/wechatshop/addCart', params).then(data => {
      http.getCartCount();
    }).catch(error => {
      wx.showToast({
        icon: 'none',
        title: '添加购物车失败,请重新添加'
      })
    });
  },
  classifySwitch: function(event) {
    let index = event.target.dataset.index;
    let id = this.data.classifys[index].id;
    this.setData({
      activeClassify: index
    });

    this.getProduct(id);
  },
  getImageUrl(id) {

  },
  getProduct(type_id) {
    let _this = this
    let cnd = ['type_id', '=', type_id];
    let domain = [cnd];
    let data = {
      model: 'wechatshop.product',
      field: 'id,name,sale_price',
      domain: JSON.stringify(domain)
    };
    http.request('/wechatshop/api/object/get', data).then(data => {
      for (let i = 0; i < data.length; i++) {
        data[i].image_url = http.requsetImageUrl('wechatshop.product', 'image_url', data[i].id);
      }
      _this.setData({
        products: data
      })
    }).catch(error => {
      wx.showToast({
        icon: 'none',
        title: '连接丢失,请重新连接'
      });
    })

  },

  refresh(){
    let data = {
      model: 'wechatshop.product.type',
      field: 'id,name'
    }

    http.request(
      '/wechatshop/api/object/get',
      data
    ).then(data => {
      if (data.length > 0) {
        let id = data[0].id;
        this.getProduct(id);
      }
      this.setData({
        classifys: data
      });
    }).catch(error => {
      wx.showToast({
        icon: 'none',
        title: '连接丢失,请重新连接'
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.refresh();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})